var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var page = 1;
var inviteuid = '';

var hb_info = '';

var screen_w = 320;
var screen_h = 568;

var timer = '';
// 八戒---------

var distant = 0;
var price = 0;
var hot = 0;
// ---------------
Page({
  data: {
    util: util,
    tc: 1,
    org_name: '',
    bottom_nav_data: [],
    isIphone_x: false,
    nav_bgColor: '#ffffff',

    screen_w: 320,
    tagTitle_bg_w: 40,

    view_order: '', //视图顺序
      logo_urls: '',//顶图
      swiperImgUrls: [],//轮播图
      gonggaoList: [],//公告
      topmenuInfos: [],//顶部分类菜单
      tietu_urls: '',//贴图区
      zixunfenlei: '', //咨询分类
      top_menu_bg_color: '#fafafa',//顶部菜单背景颜色
      top_menu_item_w: 70, //
      top_menu_img_w_h: 37.5,//顶部菜单图片宽高

      menu_item_w: 90, //
      menu_img_w_h: 37.5,//菜单图片宽高

      tuijianData:[],//店长推荐（置顶）
      tuijianOb: '',

      djJingxuanData: [],//冬季精选
      jingxuanOb: '',

      xinpin_data: [],//新品
      xinpinOb: '',

      goodsTypeArray: '',//商品分类区
      fenleiOb: '',

      mendian_data:'',//门店／经销商
      ghsData:[],

      indicatorDots: true,
      autoplay: true,
      interval: 4000,
      duration: 600,
      startTime:0, 

      userInfo: null,
      token: '',
      loginuid:'',
      
      userphotos: [],

      isIphone:false,

      isShow: false,

      itemViewWidth: 105,
      itemViewHeight: 158,

      goodsImgView_h: 160,

      swiper_h: 160,

      contact_phone: '',

      hongbaoInfo: '',
      curTime: 0,
      colorIndex: 0,

      guanggao_link: '',

      gg_img_w: 290,
      gg_img_h: 290*4/3,

      markers: [{
        iconPath: "/images/map_sign.png",
        id: 0,
        latitude: 23.016357,
        longitude: 113.103185,
        width: 20,
        height: 35
      }],

      colorSet: '',

      animation:'',//广告动画
      screen_h: 480,


      AbanList: [],
      BbanList:[],
      guojibanList:[],
      fenlei0class: "font-weight:bold;color:#4595FD;",
      fenlei1class: "",
      fenlei2class: "",

      line0: "height:8rpx;",
      line2: "",
      line3: "",

      myhao: '',
      //八戒--------
      showMoreAct: false,
      showMoreAttr: false,
      actArr: [{ type: '首', title: '新学员入学优惠信息' },
              { type: '减', title: '优惠信息' },
              { type: '特', title: '超值课程' }],
      // actArr: [{ type: '首', title: '新用户下单立减17元' },
      //   { type: '减', title: '满23减5元 满43减10元 满70减18元' },
      //   { type: '特', title: '超值20元套餐' }]
      // ------------------


  },

  allGoodsTypeArray: '',

  onLoad: function (data) {
    console.log("xxxxxxxxxxxxxxxxxxxxxxx", data);
    var tc = app.get_tc();
    var that = this;
    that.mySetData({
      tc: tc,
    });
    wx.showLoading({
      title: tc == 1 ? '加載中' : '加载中',
      mask: 'true'
    });


    hb_info = '';
    //获取绑定orgid信息
    app.GetUserInfo(util.orgid, function (res) {
      console.log("绑定机构信息：", res);
      let orgName = (that.data.tc == 1 ? res.uname_f : res.uname);
      wx.setNavigationBarTitle({
        title: orgName
      });
      
      that.mySetData({
        org_name: orgName
      })
    });
    
    //初始化底部导航
    var b_nav_data = app.getBottomNavData('index/index', function (data) {
      that.mySetData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor
      });
    });

    wx.getSystemInfo({
      success: function (res) {
        var isiPhone = (res.model.indexOf('iPhone') >= 0);
        screen_w = res.windowWidth;
        screen_h = res.windowHeight;
        var width = (res.windowWidth / 2) - (res.windowWidth / 8);
        var height = width + 1;
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.mySetData({
          tc: app.get_tc(),
          isIphone: isiPhone,
          isIphone_x: isIphone_x,
          screen_w: screen_w,
          screen_h: res.windowHeight,
          tagTitle_bg_w: (screen_w/320) * 40,
          itemViewWidth: width,
          itemViewHeight: height,
          goodsImgView_h: (screen_w - 30) / 2,
          swiper_h: screen_w / 2,
          top_menu_item_w: (screen_w - 24) / 4,
          top_menu_img_w_h: 37.5 * (screen_w / 320),

          menu_item_w: (screen_w - 24) / 4,
          menu_img_w_h: 70 * (screen_w / 320),

          gg_img_w: screen_w - 30,
          gg_img_h: (screen_w - 30) * 4 / 3,
          search_w: res.windowWidth - 96
        });
        
      }
    });
    that.mySetData({
      windowWidth: wx.getSystemInfoSync().windowWidth,
      windowHeight: wx.getSystemInfoSync().windowHeight
    }) 

    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "wxcheck"
      },
      success: function (responseData) {
        app.isShow = responseData.data.isShow;
        that.mySetData({
          isShow: responseData.data.isShow
        });
        
      }
    });
 

    // 1 - 轮播图; 2 - 顶图; 3 - 顶部菜单; 4 - 精选区
    // 5 - 推荐区; 6 - 新品区; 7 - 分类区; 8 - 经销商／门店区
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "areaorder",
        "uid": util.orgid
      },
      success: function (responseData) {
        console.log("视图顺序：", responseData.data)
        that.mySetData({
          view_order: responseData.data
        });

        //读取所有数据
        that.loadSwiperImage('');

      }
    });
    
    //是否是从分享进来的
    inviteuid = data.inviteuid ? data.inviteuid : '';
    
    

    //获取关于等信息
    app.getAllAbout('contact', function(res){
      that.mySetData({
        contact_phone: res
      })
    });

  },

  setDataCount: 0,
  mySetData:function(data){
    this.setDataCount ++;
    console.log("setDataCount : " + this.setDataCount, data);
    this.setData(data)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this;
    //获取颜色配置
    app.getColorSetData(function (color) {
      that.mySetData({
        colorSet: color
      })
      that.resetNavColor();
    });

    this.animation = wx.createAnimation({
      // 动画持续时间，单位ms，默认值 400
      duration: 300,
      /**
       * http://cubic-bezier.com/#0,0,.58,1  
       *  linear  动画一直较为均匀
       *  ease    从匀速到加速在到匀速
       *  ease-in 缓慢到匀速
       *  ease-in-out 从缓慢到匀速再到缓慢
       * 
       *  http://www.tuicool.com/articles/neqMVr
       *  step-start 动画一开始就跳到 100% 直到动画持续时间结束 一闪而过
       *  step-end   保持 0% 的样式直到动画持续时间结束        一闪而过
       */
      timingFunction: 'linear',
      // 延迟多长时间开始
      delay: 0,
      /**
       * 以什么为基点做动画  效果自己演示
       * left,center right是水平方向取值，对应的百分值为left=0%;center=50%;right=100%
       * top center bottom是垂直方向的取值，其中top=0%;center=50%;bottom=100%
       */
      transformOrigin: 'center bottom 0',
    });
  },

  onShow: function(){
    //读取红包弹出广告信息
    this.loadHongbaoList();
    // this.startTimer();
  },

  // 定时器
  startTimer: function () {
    var that = this;
    var timer = setTimeout(function () {
      var count = that.data.colorIndex + 1;
      that.mySetData({
        colorIndex: count
      })
      that.startTimer();
    }, 500);
  },

  onHide: function () {
    clearTimeout(timer);
  },

  resetNavColor: function(){
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';

    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
    
  },

  getGoodsClassly: function () {
    //读取商品分类数据
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "goodstype",
        "tc": that.data.tc
      },
      success: function (responseData) {
        console.log("商品分类数据：", responseData.data);
        var goodsType = responseData.data;
        if (goodsType.msg) {
          wx.hideLoading();
        } else {
          that.allGoodsTypeArray= goodsType;
          for (var i = 0; i < goodsType.length; i++) {
            that.loadFenleiGoodsData(goodsType[i], i);
          }
        }
      }
    });
  },


  //获取广告信息
  loadGuanggaoImage: function () {
    
      var that = this;
      var params = {
        "publickey": util.publiccode,
        "ac": "getadlist"
      };
      util.api({
        data: params,
        success: function (responseData) {
          console.log("广告数据：", responseData);
          var result = responseData.data;
          if (result && result.length > 0) {
            for(var i = 0; i < result.length; i++){
              var gdData = result[i];
              var key = "guanggao" + gdData.id;//本地缓存key
              var count = parseInt(gdData.preday ? gdData.preday : '1');//每天最大显示次数
              var startTime = parseInt(gdData.stime);//开始显示时间
              var endTime = parseInt(gdData.etime);//结束显示时间
              var curTime = parseInt(new Date().getTime() / 1000);
              if (startTime <= curTime && curTime <= endTime  //在规定时段内显示
                && parseInt(gdData.coinnum) > 0  //广告点数还没用完
                && app.getShowGuanggaoSign(key, count)) {//今天还有显示额度
                //广告
                result[i].key = key;
                that.mySetData({
                  guanggao_link: result[i]
                });
                break;
              }
            }
          }
        }
      });
    
  },

  //获取红包列表信息
  loadHongbaoList: function () {
    var that = this;
    var params = {
      "publickey": util.publiccode,
      "ac": "hongbaolist",
      "uid": util.orgid,
    };
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("红包列表信息：", result);
        if (result && result.length > 0) {
          var time = parseInt((new Date().getTime()) / 1000);
          if (time <= result[0].endtime) {
            that.mySetData({
              hongbaoInfo: result[0],
              curTime: time,
            })
            if (time >= result[0].starttime && time <= result[0].endtime) {
              that.mySetData({
                guanggao_link: result[0]
              })
            } else {
              that.loadGuanggaoImage();
            }
          } else {
            that.loadGuanggaoImage();
          }
          
        } else {
          that.loadGuanggaoImage();
        }
      }
    });
  },

  imageLoaded: function(e){
    var that = this;
    var data = e.currentTarget.dataset.info;
    var showTime = parseInt(data.showtime);
    setTimeout(function () {
      that.animation.translateY(-that.data.screen_h).step();
      that.mySetData({
        animation: that.animation.export(),
      })
      //计费
      if (that.data.loginuid && that.data.token) {//登录用户才计费
        that.adcoindown(data.id);
      }
    }, showTime);

    this.animation.translateY(this.data.screen_h).step();
    that.mySetData({
      animation: this.animation.export(),
    });
    //更新广告显示标识
    console.log("更新广告标识：", data);
    app.setShowGuanggaoSign(data.key);
    
  },

  //扣除广告费用
  adcoindown: function (adid){
    // 请求类型：post
    // 参数：ac - adcoindown标识接口
    // id - 广告id
    // downcoin - 扣除计费点数数值
    // 返回数据：res - true成功 false- 失败
    var that = this;
    var privatekey = utilMd5.hexMD5(this.data.loginuid + 'adcoindown' + this.data.token);
    var params = {
      ac: "adcoindown",
      privatekey: privatekey,
      uid: this.data.loginuid,
      id: adid,
      downcoin: 1
    };
    util.api({
      data: params,
      method: 'POST',
      success: function (responseData) {
        console.log('扣除广告费用点数: ', responseData);
      }
    });
  },


  dealAllIndexData:function(allDataArr){
    let logo_urls_l = [];//index == 2
    let topmenuInfos_l = [];//index == 3
    let swiperImgUrls_l = []; // index == 1
    let jingxuanOb_l = [];//index == 4
    let tuijianOb_l = []; //index == 5
    let xinpinOb_l = []; // index == 6
    let fenleiOb_l = []; // index == 7
    let mendian_data_l = []; // index == 8
    let tietu_urls_l = []; // index == 11
    let zixunfenlei_l = []; // index == 12
    let gonggaoList_l = [];//index == 13
    allDataArr.forEach(function (m, i) {
      let index = parseInt(m.block);
      if (index == 2) {
        logo_urls_l = logo_urls_l.concat(m);
      } else if (index == 3) {
        topmenuInfos_l = topmenuInfos_l.concat(m);
      } else if (index == 1) {
        swiperImgUrls_l = swiperImgUrls_l.concat(m);
      }
      else if (index == 4) {
        jingxuanOb_l = jingxuanOb_l.concat(m);
      } else if (index == 5) {
        tuijianOb_l = tuijianOb_l.concat(m);
      } else if (index == 6) {
        xinpinOb_l = xinpinOb_l.concat(m);
      } else if (index == 7) {
        fenleiOb_l = fenleiOb_l.concat(m);
      } else if (index == 8) {//门店
        mendian_data_l = mendian_data_l.concat(m);
      } else if (index == 11) {
        tietu_urls_l = tietu_urls_l.concat(m);
      } else if (index == 12) {
        zixunfenlei_l = zixunfenlei_l.concat(m);
      } else if (index == 13) {
        gonggaoList_l = gonggaoList_l.concat(m);
      }
    });

    let that = this;
    let topItem_w = 0;
    let topItem_color = '';
    if (logo_urls_l.length > 0) {
      logo_urls_l.forEach(function (m, i) {
        var col = parseInt(m.col);
        col = col == 0 ? 1 : col;
        logo_urls_l[i].img_w = (screen_w - (col - 1) * 5) / col;
        console.log("顶图宽2222：" + m.img_w + "; col = " + col);
      });
    }
    if (topmenuInfos_l.length > 0) {
      var colCount = topmenuInfos_l[0].col == '0' ? 4 : parseInt(topmenuInfos_l[0].col);
      topItem_w = (screen_w - 24) / colCount;
      topItem_color = topmenuInfos_l[0].bgcolor ? topmenuInfos_l[0].bgcolor : '#fafafa';
        console.log('that.data.topmenuInfos------------->>>>', topmenuInfos_l)
    }
    if (jingxuanOb_l.length > 0) {
      var item_data = jingxuanOb_l[0];
      var colCount = item_data.col == '0' ? 1 : parseInt(item_data.col);
      var w_h = (screen_w - (colCount + 1) * 5) / colCount;
      item_data.w_h = w_h;
      console.log("精选数据", item_data)
    }
    if (tuijianOb_l.length > 0) {
      var item_data = tuijianOb_l[0];
      var colCount = item_data.col == '0' ? 1 : parseInt(item_data.col);
      var w_h = (screen_w - (colCount + 1) * 7) / colCount;
      item_data.w_h = w_h;
    }
    if (xinpinOb_l.length > 0) {
      var item_data = xinpinOb_l[0];
      var colCount = item_data.col == '0' ? 1 : parseInt(item_data.col);
      var w_h = (screen_w - (colCount + 1) * 7) / colCount;
      item_data.w_h = w_h;
    }
    if (fenleiOb_l.length > 0) {
      var item_data = fenleiOb_l[0];
      var colCount = item_data.col == '0' ? 1 : parseInt(item_data.col);
      var w_h = (screen_w - (colCount + 3) * 10) / colCount;
      item_data.w_h = w_h;
    }
    if (mendian_data_l.length > 0) {//门店 
      console.log('mendian:', mendian_data_l)
    }
    if (tietu_urls_l.length > 0) {
      tietu_urls_l.forEach(function (m, i) {
        var col = parseInt(m.col);
        col = col == 0 ? 1 : col;
        tietu_urls_l[i].img_w = screen_w / col;
        console.log("贴图宽：" + m.img_w + "; col = " + col);
      });
    }
    if (zixunfenlei_l.length > 0) {
      console.log("index == 12", result);
      zixunfenlei_l.forEach(function (m, i) {
        var col = parseInt(m.col);
        col = col == 0 ? 1 : col;
        zixunfenlei_l[i].img_w = screen_w / col;
        console.log("贴图宽：" + m.img_w + "; col = " + col);
      });
    }

    that.mySetData({
      logo_urls: logo_urls_l.length > 0 ? logo_urls_l : '',
      topmenuInfos: topmenuInfos_l.length > 0 ? topmenuInfos_l : '',
      top_menu_item_w: topItem_w,
      top_menu_bg_color: topItem_color,
      swiperImgUrls: swiperImgUrls_l.length > 0 ? swiperImgUrls_l : '',
      jingxuanOb: jingxuanOb_l.length > 0 ? jingxuanOb_l[0] : '',
      tuijianOb: tuijianOb_l.length > 0 ? tuijianOb_l[0] : '',
      xinpinOb: xinpinOb_l.length > 0 ? xinpinOb_l[0] : '',
      fenleiOb: fenleiOb_l.length > 0 ? fenleiOb_l[0] : '',
      shopViewName: mendian_data_l.length > 0 ? mendian_data_l[0].navtitle : '',
      mendian_data: mendian_data_l.length > 0 ? mendian_data_l : '',
      tietu_urls: tietu_urls_l.length > 0 ? tietu_urls_l : '',
      zixunfenlei: zixunfenlei_l.length > 0 ? zixunfenlei_l : '',
      gonggaoList: gonggaoList_l.length > 0 ? gonggaoList_l : ''
    })
    
    if (fenleiOb_l.length > 0){
      //读取商品分类数据
      that.getGoodsClassly();
    }
    if (jingxuanOb_l.length > 0){
      that.loadGoodsListData(0, 1);
    }
    if (tuijianOb_l.length > 0) {
      that.loadGoodsListData(1, 0);
    }
    if (xinpinOb_l.length > 0){
      that.loadGoodsListData(0, 0);
    }
    
    // that.logo_urlsTC();
    // that.topmenuInfosTC();
  },

//index 001  幻灯片数据
  loadSwiperImage: function(index){
    var that = this;
    var params = {
      "publickey": util.publiccode,
      "ac": "indexslide",
      "uid": util.orgid,
      "block": index,
      "tc": that.data.tc
    };
    util.api({
      data: params,
      success: function (responseData) {
        console.log(index + "-- swiper image:", responseData);
        var result = responseData.data;
        if (result && result.length > 0) {
          
          that.dealAllIndexData(result);

        }
        wx.hideLoading();
      }
    });
  },

  swiperAction: function (e) {
    var that = this;
    var data = e.currentTarget.dataset.info;
    app.saveFormId(e.detail.formId);
    console.log("swiper data:", data);
    if (data) {
      var go_type = data.type;
      var go_id = data.data;
      if (go_type == "topic" && go_id) {//去详情页
        var url = "/pages/detail/detail?topicid=" + go_id;
        wx.navigateTo({ url: url })
      } else if (go_type == "url") {
        var url = go_id;
        if (url.indexOf('/pages/') >= 0) {
          wx.navigateTo({ url: url })
        } else if (url.indexOf('showToast') >= 0){
          this.pindanAction();
        } else{
          // app.dialog('未定义跳转' + url, 'success');
        }
      } else {
        // app.dialog('未定义跳转：' + go_type + '--' + go_id, 'success');
      }
    }
  },

  addWater:function(){
    var that=this;
    
    if (!that.data.myhao[0]) {
      wx.showModal({
        title: '提示',
        content: that.data.tc == 1 ? '請按確定進行掃碼獲取臺號' : '请按确定进行扫码获取台号',
        confirmText: that.data.tc == 1 ? '確定掃碼' : '确定扫码',

        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            that.scancode();
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }

      })
    } else {
      var tc = app.get_tc();
      wx.showModal({
        // title: tc == 1 ? '著數皇' : '著数皇',
        title: tc == 1 ? '您當前的臺號為：' + that.data.myhao[0].project : '您当前的台号为：' + that.data.myhao[0].project,
        content: tc == 1 ? '著數皇真誠為您服務' : '著数皇真诚为您服务',
        confirmText: tc == 1 ? '確認加水' : '确认加水',

        success: function (res) {

          if (res.confirm) {
            wx.showLoading({
              title: tc == 1 ? '請稍後片刻' : '请稍后片刻',
            })

            setTimeout(function () {
              wx.hideLoading()
            }, 2000)
            that.zswtuisong(that.data.myhao[0].project);
          }

        }
      })

    }
  },



  //获取我的台号
  getMyhao:function(){
    
    var that = this;
     util.api({
      method: "get",
      data: {
        ac: "getmyhao",
        uid: that.data.loginuid,
        orgid: that.data.postuid,
        type:9
      },
      
      success: function (responseData) {
        console.log("调试--我的排号信息接口:", responseData.data);
 
        var resultData = responseData.data;
        if (resultData.res != false) {
          if (new Date().getTime() - resultData[0].ctime * 1000 < 120 * 60 * 1000) {
            that.mySetData({
              myhao: resultData,
            });
            console.log("调试--new Date().getTime()", new Date().getTime());
            console.log("调试---resultData[0].ctime*1000:", resultData[0].ctime * 1000);
            console.log("调试--new Date().getTime()-resultData[0].ctime*1000:", new Date().getTime() - resultData[0].ctime * 1000);
          } else {
            that.delMyhao();
          }      
          
        }
        if (that.data.addwater == 1) {
          that.data.addwater == 0;
          that.addWater();
        }
        
      }
    });
  },
  

  zswtuisong:function (taihao){
    var that = this;
    

    var that = this;
    var privatekey = utilMd5.hexMD5(this.data.loginuid + 'zswtuisong' + this.data.token);
    var params = {
       publickey:util.publiccode,
      ac:"zswtuisong",
      uid:that.data.loginuid,
      orgid: util.orgid,
      taihao:taihao,
      touid:that.data.loginuid,
      project: '加水',
      privatekey: privatekey
  
    };
    util.api({
      data: params,
      method: 'POST',
      success: function (responseData) {
        console.log('tuisong: ', responseData);
        var url = responseData.data.url;
        console.log('tuisong url: ', url);
        wx.request({
          url: url,
          data: '',
          method: 'get',
          success: function (res) {
            console.log(res)
            
            wx.showModal({
              title: that.data.tc == 1 ? '你的申請已受理!' : '你的申请已受理!',
              content: that.data.tc == 1 ? '著數皇真誠為您服務' : '著数皇真诚为您服务',
              confirmText: that.data.tc == 1 ? '確認' : '确认',

              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          },
          fail: function (err) {
            console.log('request fail ', err);
            wx.showModal({
              title: that.data.tc == 1 ? '你的申請暫未成功!' : '你的申请暂未成功!',
              content: that.data.tc == 1 ? '著數皇真誠為您服務' : '著数皇真诚为您服务',
              confirmText: that.data.tc == 1 ? '確認' : '确认',

              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          },
          complete: function (res) {
            console.log("request completed!");
          }

        })

      }
    });

  },
  
  //广告图响应动作
  guanggaoAction: function (e) {
    var data = e.currentTarget.dataset.info;
    if (data) {
      var go_type = data.linktype;
      var link = data.linkurl;
      console.log("go_type = " + go_type + "; link = " + link);
      if (go_type == "0" && link) {//去详情页
        var url = "/pages/detail/detail?topicid=" + link;
        console.log("跳到详情页面 url = " + url + "; link = " + link);
        wx.navigateTo({ url: url })
      } else if (go_type == "1" && link.indexOf('/pages/') >= 0) {
        console.log("跳到自定义页面 link = " + link);
        wx.navigateTo({ url: link })
      }
    }
  },

  loadFenleiGoodsData: function (goodsTypeOb, index) {
    var that = this;
    var goodsId = goodsTypeOb.goods_id;
    var params = {
      publickey: util.publiccode,
      ac: "topiclist",
      topictype: '4',
      toporder: '1',
      tc: that.data.tc,
      orgid: util.orgid,
      gtype: goodsId,
      ordernum: 1,//按排序字段排序 0和不传是不安这个排，1是升序，2是降序
      zhiding: '1',
      page: 1,
      num: 10
    };
    console.log("商品参数：", params);
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("商品数据" + goodsId + ": ", result);
        if (result.msg) {
          goodsTypeOb.goodsArray = [];
          goodsTypeOb.noData = true;
        } else {
          var count = result.length;
          result.forEach(function (m, i) {
            result[i].count = count;
            if(util.orgid==17784){
              if(m.guige.indexOf("|")>0){
                var guigeTitleArray=m.guige.split("|");
                m.guigeTitleArray = guigeTitleArray;
                console.log("guigeTitleArray", guigeTitleArray)
              }
            }
          });
          goodsTypeOb.goodsArray = result;
          goodsTypeOb.noData = false;
        }
        var goodsTypeArr = that.allGoodsTypeArray;
        goodsTypeArr[index] = goodsTypeOb;
        that.mySetData({
          goodsTypeArray: goodsTypeArr
        })
        console.log("商品数据goodsTypeArray" , that.data.goodsTypeArray);
        wx.hideLoading();
      }
    });
  },

  loadGoodsListData: function (zhiding, jingxuan) {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "topiclist",
      topictype: '4',
      tc: that.data.tc,
      orgid: util.orgid,
      zhiding: zhiding,
      ordernum: 1,//按排序字段排序 0和不传是不安这个排，1是升序，2是降序
      shopgoodscata: jingxuan,
      page: 1,
      num: 4
    };

    // console.log("商品请求参数：", params);
    util.api({
      data: params,
      success: function (responseData) {
        console.log("zhiding:" + zhiding + "; shopgoodscata:" + jingxuan);
        console.log("商店商品数据:", responseData);
        var resData = responseData.data;
        if (!resData.msg) {
          if (zhiding == 1){//热销推荐
            that.mySetData({
              tuijianData: resData
            })
          } else if (jingxuan == 1) {//精选
            that.mySetData({
              djJingxuanData: resData
            })

            console.log("精选===>>>:", resData);
          } else { //新品上市
            that.mySetData({
              xinpin_data: resData
            })
          }
        }
        
        wx.hideLoading();
      }
    });
  },
  

  goAtherPage: function(e){
      var url = e.currentTarget.dataset.link;
      wx.navigateTo({url: url})
  },
  goAtherPageRedirect: function(e){
      app.saveFormId(e.detail.formId);  
      var url = e.currentTarget.dataset.link;
      wx.redirectTo({url: url})
  },
  //页面分享
  onShareAppMessage: function () {
    var that = this;
    var inviteuid = that.data.loginuid ? that.data.loginuid : '';
    console.log("分享id" + inviteuid);
    if(util.orgid==14939){
      return {
        title: '繁花音乐，暑假、下班放松好去处。',
        path: '/pages/index/index?&inviteuid=' + inviteuid
      };
    }else if (util.orgid == 17758) {
      return {
        title: '生酮飲料已開啟了一場現代健康革命。',
        path: '/pages/index/index?&inviteuid=' + inviteuid
      };
    } else{
      return {
        title: that.data.org_name,
        path: '/pages/index/index?&inviteuid=' + inviteuid
      };
    }
  },
  

  showEWM: function (e) {
    var shareImgUrl = e.currentTarget.dataset.imgsrc;
    console.log("图片链接：" + shareImgUrl);
    wx.previewImage({
      current: shareImgUrl,
      urls: [shareImgUrl]
    })
  },

  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    console.log("path", e.detail.value)
    console.log("path",path)
    if (path) {
      if (path.indexOf('navto:') == 0) {
        var navPath = path.slice(6);
        wx.navigateTo({
          url: navPath,
        })
      } else {
        wx.redirectTo({ url: path });
      }

    }

    path = e.detail.value.page_path;
    if (path) {
      wx.navigateTo({ url: path });
    }
  },

  makeCallPhone:function(e) {
    app.saveFormId(e.detail.formId);
    var phoneNum = e.currentTarget.dataset.number;
    console.log("phoneNum:" + phoneNum);
    wx.makePhoneCall({
      phoneNumber: phoneNum,
      success:function(e){
        console.log("make call success:", JSON.stringify(e));
      },
      fail:function(e){
        console.log("make call fail:", JSON.stringify(e));
      }
    })
  },

  goHongbaoPage: function(e){
    var hb_info = e.currentTarget.dataset.info;
    var hongbaoId = hb_info.hongbaoid;
    var path = "/pages/hongbao/hongbao?hongbaoid=" + hongbaoId + "&shareuid=" + util.orgid;
    wx.navigateTo({
      url: path,
    })
  },

  goMapView: function (e) {
    var lat = 23.010426;
    var lon = 113.096518;
    var tc = this.data.tc;
    wx.openLocation({
      latitude: lat,
      longitude: lon,
      scale: 18,
      name: tc == 1 ? '煌圖廣告' :'煌图广告',
      address: tc == 1 ? '佛山市禪城區季華四路盈科億家陶瓷衛浴世界東區B2座三樓322號' : '佛山市禅城区季华四路盈科亿家陶瓷卫浴世界东区B2座三楼322号',
    })
  },
  goMapViewZeai: function (e) {
    var lat = 22.184101;
    var lon = 113.555919;
    // 22.184101, 113.555919
    var tc = this.data.tc;
    wx.openLocation({
      latitude: lat,
      longitude: lon,
      scale: 18,
      name: tc == 1 ?'澤愛托兒所':'泽爱托儿所',
      address: tc == 1 ? '澳門新口岸栢嘉街490號帝景苑地下BL' : '澳门新口岸栢嘉街490号帝景苑地下BL',
    })
  },
  goMapViewIFI: function (e) {
    var lat = 22.284320;
    var lon = 114.155660;
    // 22.198730,113.556790 MACAU
    // 22.284320, 114.155660 HONGKONG
    var tc = this.data.tc;
    wx.openLocation({
      latitude: lat,
      longitude: lon,
      scale: 18,
      name: tc == 1 ?'IFI玥輝設計':'IFI Design Limited',
      // address: tc == 1 ? '澳門士多鳥拜斯大馬路 57 號瓊苑大廈 A' : 'Avenida de Sidonio Pais 57, Edf. Keng Yuen r/c A,  Macau',
      address: tc == 1 ? '香港上環德輔道中317-319號 啟德商業大廈11樓' : '11 / F, Eic commercial building, 317-319 De Fu Road, Sheung Wan, Hongkong.',
    })
  },



  //着数王加水扫码获取台号
  scancode: function () {
    var that = this;
    wx.scanCode({
      success: function (responseData) {
        console.log(responseData);
        console.log(responseData.result);
        console.log(responseData.result.taihao);
        that.mySetData({
          taihao: responseData.result,
        })
        that.bookTable();
      }
    })
  },

  //删除我的过期信息
  delMyhao: function () {

    var that = this;
    util.api({
      method: "get",
      data: {
        ac: "delmyhao",
        uid: that.data.loginuid,
        orgid: that.data.postuid,
        type: 9
      },

      success: function (responseData) {
        console.log("调试--delmyhao信息接口:", responseData.data);

      }
    });
  },

  bookTable: function () {
    var that = this;
    console.log('that.toDate(new Date().getTime()/1000)', that.toDate(new Date().getTime() / 1000));
    var privatekey = utilMd5.hexMD5(that.data.loginuid + 'yuyue' + that.data.token);
    var data = {
      ac: "yuyue",
      uid: that.data.loginuid,
      orgid: that.data.postuid,
      privatekey: privatekey,
      userNum: '',
      btime: that.toDate(new Date().getTime() / 1000),
      username: '',
      // project: that.data.desks[e.detail.value.desk],
      project: that.data.taihao,
      phone: '',
      address: '',
      type: 9
    };
    util.api({
      method: "post",
      data: data,

      success: function (responseData) {
        console.log("调试--预约接口接口:", responseData.data);
        if (responseData.data.res == true) {
          var contentname = that.data.tc == 1 ? '已成功訂位' : '';
          wx.showToast({
            title: contentname,
          })
          app.dialogToast(contentname, "success", function () {
          });
          that.getMyhao();
        } else {
          var contentname = that.data.tc == 1 ? '訂位失敗' : '';
          wx.showToast({
            title: contentname,
          })
        }

      }
    });
  },

  //时间戳转换时间  
  toDate: function (number) {
    var n = number * 1000;
    var date = new Date(n);
    var Y = date.getFullYear() + '.';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '.';
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
    var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    console.log(Y + M + D + "  " + H + ':' + m)
    return (Y + M + D + "  " + H + ':' + m)

  },

  //著数王标题
  topmenuInfosTC:function(){
    var that= this;
    var arr = that.data.topmenuInfos;
    if (util.orgid == '12545' || util.orgid == '20510'){
      for (var i = 0; i < arr.length; i++) {
        let navArr = arr[i].navtitle.split(':')
        arr[i].navtitle = that.data.tc == 1 ? navArr[0] : navArr[1];
        if (arr[i].data.indexOf(":") > 0) {
          let navDataArr = arr[i].data.split(':')
          arr[i].data = that.data.tc == 1 ? navDataArr[0] : navDataArr[1];
        }
      }
    }
    that.mySetData({
      topmenuInfos: arr
    })
  },
  //标题中英切换
  logo_urlsTC:function(){
    var that= this;
    var arr = that.data.logo_urls;
    if (util.orgid == '12545' || util.orgid == '20510'){
      for (var i = 0; i < arr.length; i++) {
        let navArr = arr[i].navtitle.split(':')
        arr[i].navtitle = that.data.tc == 1 ? navArr[0] : navArr[1];
        if (arr[i].data.indexOf(":") > 0) {
          let navDataArr = arr[i].data.split(':')
          arr[i].data = that.data.tc == 1 ? navDataArr[0] : navDataArr[1];
        }
      }
    }
    that.mySetData({
      logo_urls: arr
    })
  },
  //AsiaPruvit 日期
  setCurrentDayString: function () {
    var c_obj = new Date()
    var a = (c_obj.getMonth() + 1) + '月' + c_obj.getDate() + '日' + " 星期" + "日一二三四五六".charAt(c_obj.getDay());
    this.mySetData({
      currentDay:a
    })

  },

  splitNavtitle: function (navList) {
    var that = this;
    for (var i = 0; i < navList.length; i++) {
      let title = navList[i].navtitle;
      if (title.indexOf(":") > 0) {
        let miniArr = title.split(':')
        if (miniArr.length == 2) {
          if (!navList[i].summary) {
            navList[i].summary = '';
          }
          navList[i].navtitle = miniArr[0];
          navList[i].summary = miniArr[1];
          console.log('navtitle.summary', navList[i].summary)

        } else {

        }
        console.log('navtitle.summary', navList[i].summary)
      } else {
        if (!navList[i].summary) {
          navList[i].summary = '';
        }
        console.log('navtitle.summary', navList[i].summary)
      }

    }
    return navList
  },

  // 读取门店
  loadGHS: function (cpage) {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getghs",
      orgid: util.orgid,
      page: cpage,
      num: 10
    }
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("供货商数据17784：", result);
        that.mySetData({
          ghsData: that.data.ghsData.concat(result)
        });
        that.loadGoodsToGHS();
      }
    });
  },

  loadGoodsToGHS: function () {
    console.log("loadGoodsToGHS17784：");
    var that = this;

    that.getGoodsClassly();
  },
  //门店优惠活动
  showMoreActivity:function(){
    this.mySetData({
      showMoreAct:this.data.showMoreAct==true?false:true
    })
  },

  distantOrder: function () {
    hot = 0;
    page = 1;
    if (distant == 0 || distant == 1) {
      distant = 2;
    } else {
      distant = 1;
    }
    this.mySetData({
      hotOrder: hot,
      distantOrder: distant,
      toporder: '',
      // goodTypeName: '',
      hidecata: true
    });
    // this.loadGoodsListData(1);
  },
  priceOrder: function () {
    hot = 0;
    page = 1;
    if (price == 0 || price == 1) {
      price = 2;
    } else {
      price = 1;
    }
    this.mySetData({
      hotOrder: hot,
      priceOrder: price,
      toporder: '',
      // goodTypeName: '',
      hidecata: true
    });
    // this.loadGoodsListData(1);
  },

  hotOrder: function () {
    price = 0;
    page = 1;
    if (hot == 0 || hot == 1) {
      hot = 2;
    } else {
      hot = 1;
    }
    this.mySetData({
      hotOrder: hot,
      priceOrder: price,
      // goodTypeName: '',
      toporder: '',
      hidecata: true
    });
    // this.loadGoodsListData(1);
  },

  // 读取主题
  loadAttributeGroups: function () {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getAttributeGroups",
      orgid: util.orgid,
    }
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("主题数据17784：", result);
        that.mySetData({
          attrList: result
        });
      }
    });
  },
  //更多主题
  showMoreAttr: function () {
    this.mySetData({
      showMoreAttr: this.data.showMoreAttr == true ? false : true
    })
  },

  selectAddress: function () {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        console.log("选择地址：", res);
        var userInfo = that.data.userInfo;
        userInfo.addresschoose = res.address;
        userInfo.lon = res.longitude;
        userInfo.lat = res.latitude;

        that.mySetData({
          userInfo: userInfo
        })
      },
    })
  },
  //获取定位信息
  getMyLocation: function () {
    var that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log("定位信息：", res);
        that.mySetData({
          latitude: res.latitude,
          longitude: res.longitude
        });
        // var userInfo = that.data.userInfo;
        // userInfo.addresschoose = res.address;
        // userInfo.lon = res.longitude;
        // userInfo.lat = res.latitude;

        // that.mySetData({
        //   userInfo: userInfo
        // })
        // that.load(true);
      },
      fail: function () {
        wx.showModal({
          title: '提示',
          content: '获取定位信息失败，这将影响您的使用体验，是否重新设置授权？',
          showCancel: true,
          cancelText: "否",
          confirmText: "是",
          success: function (res) {
            if (res.confirm) {
              wx.getSetting({
                success: function (res) {
                  console.log(res);
                  console.log('success');
                  that.getMyLocation();
                },
                fail: function () {
                  console.log('fail');
                }
              })
            } else if (res.cancel) {
              console.log('用户点击否')
              // that.load(true);
            }
          }
        })
      }
    })
  },

  // 获取每个商品标签属性
  getAttribute: function (good) {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getAttribute",
      orgid: util.orgid,
      uid: that.data.loginuid,
      groupId: good.groupId
    };

    console.log("商品属性请求参数：", params);
    util.api({
      data: params,
      success: function (responseData) {
        console.log("商品属性:", responseData.data);
        var result = responseData.data;
        if (result.length > 0) {
          return responseData.data
        }else{
          return []
        }
      }
    });
  },
  //IFI电话下拉选项改变值
  bindGhsPickerChange: function (e) {//选项改变触发事件
    var that = this;
    this.mySetData({
      ghsIndex: e.detail.value
    })
    e.currentTarget.dataset.number = that.data.ghsList[e.detail.value].phone
    that.makeCallPhone(e)
  },
  

  
})
